// 通用工具函数
const common = {
    // 格式化价格
    formatPrice(price) {
        if (price === null || price === undefined) {
            return '0.00';
        }

        let priceNumber = Number(price);

        if (isNaN(priceNumber)) {
            return '0.00';
        }
        return priceNumber.toFixed(2);
    },

    // 格式化地址，避免重复显示省市区
    formatAddress(addressData) {
        if (!addressData) return '';

        // 如果已经有格式化好的地址，直接返回
        if (typeof addressData === 'string') return addressData;
        if (addressData.fullAddress) return addressData.fullAddress;

        // 获取地址各部分
        const province = addressData.province || '';
        const city = addressData.city || '';
        const district = addressData.district || '';
        const detail = addressData.detailAddress || addressData.detail || '';

        // 创建一个Set来存储不重复的地址部分
        const uniqueParts = new Set();

        // 添加省份
        if (province) {
            uniqueParts.add(province);
        }

        // 添加城市（如果不是省份的一部分）
        if (city && !province.includes(city)) {
            uniqueParts.add(city);
        }

        // 添加区县（如果不是省份或城市的一部分）
        if (district && !province.includes(district) && !city.includes(district)) {
            uniqueParts.add(district);
        }

        // 添加详细地址
        if (detail) {
            uniqueParts.add(detail);
        }

        // 转换为数组并连接
        return Array.from(uniqueParts).join('');
    },

    // 格式化日期
    formatDate(date, format = 'YYYY-MM-DD') {
        if (!date) return '';
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hour = String(d.getHours()).padStart(2, '0');
        const minute = String(d.getMinutes()).padStart(2, '0');
        const second = String(d.getSeconds()).padStart(2, '0');

        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hour)
            .replace('mm', minute)
            .replace('ss', second);
    },

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    // 节流函数
    throttle(func, limit) {
        let inThrottle;
        return function () {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },

    // 深拷贝
    deepClone(obj) {
        if (obj === null || typeof obj !== 'object') return obj;
        if (obj instanceof Date) return new Date(obj.getTime());
        if (obj instanceof Array) return obj.map(item => this.deepClone(item));
        if (typeof obj === 'object') {
            const clonedObj = {};
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    clonedObj[key] = this.deepClone(obj[key]);
                }
            }
            return clonedObj;
        }
    },

    // 生成唯一ID
    generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    },

    // 检查是否为空
    isEmpty(value) {
        if (value === null || value === undefined) return true;
        if (typeof value === 'string') return value.trim() === '';
        if (Array.isArray(value)) return value.length === 0;
        if (typeof value === 'object') return Object.keys(value).length === 0;
        return false;
    },

    // 显示加载提示
    showLoading(title = '加载中...') {
        uni.showLoading({
            title,
            mask: true
        });
    },

    // 隐藏加载提示
    hideLoading() {
        uni.hideLoading();
    },

    // 显示通用提示
    showToast(title, icon = 'none', duration = 2000) {
        // 避免异常:确保uni已经初始化
        if (typeof uni !== 'undefined' && uni.showToast) {
            uni.showToast({
                title: String(title),
                icon,
                duration
            });
        } else {
            console.log('[Toast]', title);
        }
    },

    // 显示成功提示
    showSuccess(title = '操作成功') {
        this.showToast(title, 'success');
    },

    // 显示错误提示
    showError(title = '操作失败') {
        this.showToast(title, 'none');
    },

    // 确认对话框
    showConfirm(content, title = '提示') {
        return new Promise((resolve) => {
            uni.showModal({
                title,
                content,
                success: (res) => {
                    resolve(res.confirm);
                }
            });
        });
    },

    // 获取系统信息
    getSystemInfo() {
        return new Promise((resolve) => {
            uni.getSystemInfo({
                success: (res) => {
                    resolve(res);
                }
            });
        });
    },

    // 获取网络状态
    getNetworkType() {
        return new Promise((resolve) => {
            uni.getNetworkType({
                success: (res) => {
                    resolve(res.networkType);
                }
            });
        });
    },

    // 拨打电话
    makePhoneCall(phoneNumber) {
        uni.makePhoneCall({
            phoneNumber,
            fail: () => {
                this.showError('拨打电话失败');
            }
        });
    },

    // 复制到剪贴板
    setClipboardData(data) {
        uni.setClipboardData({
            data,
            success: () => {
                this.showSuccess('复制成功');
            },
            fail: () => {
                this.showError('复制失败');
            }
        });
    },

    // 预览图片
    previewImage(urls, current = 0) {
        uni.previewImage({
            urls,
            current: urls[current] || urls[0]
        });
    },

    // 选择图片
    chooseImage(count = 1, sizeType = ['original', 'compressed']) {
        return new Promise((resolve, reject) => {
            uni.chooseImage({
                count,
                sizeType,
                success: (res) => {
                    resolve(res.tempFilePaths);
                },
                fail: reject
            });
        });
    },

    // 上传图片
    uploadImage(filePath) {
        return new Promise((resolve, reject) => {
            uni.uploadFile({
                url: 'http://localhost:8080/upload/image',
                filePath,
                name: 'file',
                success: (res) => {
                    try {
                        const data = JSON.parse(res.data);
                        resolve(data);
                    } catch (e) {
                        reject(e);
                    }
                },
                fail: reject
            });
        });
    }
};

export default common; 